package com.dries.security.app.authentication;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.dries.security.common.api.CommonResult;
import com.dries.security.core.enums.LoginType;
import com.dries.security.core.properties.SecurityCoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/4 10:58
 */
@Slf4j
@Component("driesAuthFailureHandler")
public class DriesAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Resource
    private SecurityCoreProperties coreProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        log.info("登录失败！");
        if (LoginType.JSON.equals(coreProperties.getBrowser().getLoginType())) {
            response.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONUtil.toJsonStr(CommonResult.failed(e.getMessage())));
        } else {
            super.onAuthenticationFailure(request, response, e);
        }


    }
}
